package com.xusheng.cli.controller.back;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xusheng.cli.common.base.MyPage;
import com.xusheng.cli.common.base.Result;
import com.xusheng.cli.common.validation.Save;
import com.xusheng.cli.common.validation.Update;
import com.xusheng.cli.entity.backAgentModule.BackAgent;
import com.xusheng.cli.entity.frontUserModule.FrontUser;
import com.xusheng.cli.entity.withdrawModule.Withdraw;
import com.xusheng.cli.entity.withdrawModule.WithdrawDTO;
import com.xusheng.cli.entity.withdrawModule.WithdrawReq;
import com.xusheng.cli.service.BackAgentService;
import com.xusheng.cli.service.FrontUserService;
import com.xusheng.cli.service.PayWithdrawService;
import com.xusheng.cli.service.WithdrawService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 提现(Withdraw)表控制层
 *
 * @author whr
 * @since 2024-03-19 17:08:43
 */
@Validated
@RestController
@RequestMapping("/api/v1/withdraw")
public class WithdrawController {
    /**
     * 服务对象
     */
    @Resource
    private WithdrawService withdrawService;
    @Resource
    private BackAgentService backAgentService;
    @Resource
    private FrontUserService frontUserService;
    @Resource
    private PayWithdrawService payWithdrawService;

    /**
     * 查询所有数据
     *
     * @param withdraw 查询实体
     * @return 所有数据
     * @author whr
     * @since 2024-03-19 17:08:43
     */
    @GetMapping("queryAll")
    public Result<List<Withdraw>> queryAll(Withdraw withdraw) {
        return Result.success(withdrawService.list(new QueryWrapper<>(withdraw)));
    }

    /**
     * 分页查询所有数据
     *
     * @param page     分页对象
     * @param withdraw 查询实体
     * @return 所有数据
     * @author whr
     * @since 2024-03-19 17:08:43
     */
    @GetMapping("queryByPage")
    public Result<Map<String, Object>> queryByPage(MyPage<Withdraw> page, WithdrawDTO withdraw) {
        DateTime beginDate = DateUtil.parse(withdraw.getBeginDate());
        DateTime endDate = DateUtil.parse(withdraw.getEndDate());
        if (StrUtil.isNotBlank(withdraw.getBeginDate())) {
            beginDate = DateUtil.beginOfDay(beginDate);
        }
        if (StrUtil.isNotBlank(withdraw.getEndDate())) {
            endDate = DateUtil.endOfDay(endDate);
        }
        LambdaQueryWrapper<Withdraw> eq = new LambdaQueryWrapper<>(new Withdraw())
                .ge(beginDate != null, Withdraw::getCreateTime, beginDate)
                .le(endDate != null, Withdraw::getCreateTime, endDate)
                .eq(withdraw.getType() != null, Withdraw::getType, withdraw.getType())
                .eq(withdraw.getState() != null, Withdraw::getState, withdraw.getState());
        MyPage<Withdraw> myPage = withdrawService.page(page, eq);
        for (Withdraw w : myPage.getRecords()) {
            if (w.getType() == 1) {
                BackAgent backAgent = backAgentService.getById(w.getUserId());
                if (backAgent != null) {
                    w.setUserName(backAgent.getName());
                }
            } else if (w.getType() == 2) {
                FrontUser user = frontUserService.getById(w.getUserId());
                if (user != null) {
                    w.setUserName(user.getAccount());
                }
            }
        }
        Map<String, Object> map = withdrawService.statisticsAmount(beginDate, endDate, withdraw.getType());
        if (map == null) {
            map = new HashMap<>();
            map.put("unsettleAmount", 0);
            map.put("settleAmount", 0);
        }
        map.put("page", myPage);
        return Result.success(map);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     * @author whr
     * @since 2024-03-19 17:08:43
     */
    @GetMapping("queryOne/{id}")
    public Result<Withdraw> selectOne(@PathVariable Serializable id) {
        return Result.success(withdrawService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param withdraw 实体对象
     * @return 新增结果
     * @author whr
     * @since 2024-03-19 17:08:43
     */
    @PostMapping("insert")
    public Result<Object> insert(@Validated(Save.class) @RequestBody Withdraw withdraw) {
        return Result.isSuccess(withdrawService.save(withdraw));
    }

    /**
     * 修改数据
     *
     * @param withdraw 实体对象
     * @return 修改结果
     * @author whr
     * @since 2024-03-19 17:08:43
     */
    @PutMapping("update")
    public Result<Object> update(@Validated(Update.class) @RequestBody Withdraw withdraw) {
        return Result.isSuccess(withdrawService.updateById(withdraw));
    }

    /**
     * 删除单条数据
     *
     * @param id 主键
     * @return 删除结果
     * @author whr
     * @since 2024-03-19 17:08:43
     */
    @DeleteMapping("delete/{id}")
    public Result<Object> delete(@PathVariable Long id) {
        Withdraw withdraw = new Withdraw();
        withdraw.setId(id);
        return Result.isSuccess(withdrawService.removeById(withdraw));
    }

    /**
     * 批量删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     * @author whr
     * @since 2024-03-19 17:08:43
     */
    @DeleteMapping("batchDelete")
    public Result<Object> batchDelete(@Validated @Size(min = 1, message = "缺少删除所需的id") @RequestParam("idList") List<Long> idList) {
        return Result.isSuccess(withdrawService.batchDelete(idList, new Withdraw()));
    }

    /**
     * 批量结算
     *
     * @param req ids paymentId
     * @return
     */
    @PostMapping("batchWithdraw")
    public Result<Object> batchSettle(@RequestBody WithdrawReq req, HttpServletRequest request) {
        payWithdrawService.createOrder(req, request);
        return Result.success();
    }

    /**
     * 手动结算
     *
     * @param req
     * @return
     */
    @PostMapping("batchWithdrawHand")
    public Result<Object> batchSettleHand(@RequestBody WithdrawReq req) {
        if (req.getIds().size() == 0) {
            return Result.error("请先选择结算订单");
        }
        List<Withdraw> withdraws = withdrawService.lambdaQuery().in(Withdraw::getId, req.getIds()).list();
        if (CollectionUtil.isNotEmpty(withdraws)) {
            List<Withdraw> collect = withdraws.stream().filter(withdraw -> withdraw.getState() < 3).collect(Collectors.toList());
            for (Withdraw withdraw : collect) {
                withdraw.setState(withdraw.getState() + 1);
            }
            return Result.isSuccess(withdrawService.updateBatchById(collect));
        } else {
            return Result.error("未查询到结算订单信息");
        }
    }
}

